import React, { useEffect, Suspense } from 'react';
import { useRoutes, useNavigate, useLocation } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { Spin } from 'antd';
import { RootState } from '../store';
import { routes as baseRoutes } from './routes';
import addDynamicRoutes from './addRoutes';

// 菜单项接口
interface MenuItem {
  index: string;
  title: string;
  path?: string;
  parentId?: string;
  type?: string;
  icon?: string;
  name?: string;
  component?: string;
  menuType?: number;
  meta?: any;
  children?: MenuItem[];
}

// 路由菜单项接口
interface RouteMenuItem {
  path: string;
  name: string;
  component: string;
  meta?: Record<string, any>;
  children?: RouteMenuItem[];
}

// 将 menu 适配为 addDynamicRoutes 需要的格式
const adaptMenuToRouteFormat = (menus: MenuItem[]): MenuItem[] => {
  // 只处理包含子菜单的项
  const routeMenus: MenuItem[] = [];
  
  menus.forEach(menu => {
    if (menu.children && menu.children.length > 0) {
      // 过滤只有path属性的子菜单
      const validChildren = menu.children.filter(child => child.path && child.component);
      if (validChildren.length > 0) {
        routeMenus.push({
          ...menu,
          children: validChildren
        });
      }
    }
  });
  
  return routeMenus;
};

const Router: React.FC = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const location = useLocation();
    const { token } = useSelector((state: RootState) => state.auth);
    const { menus } = useSelector((state: RootState) => state.menu);

    const [routes, setRoutes] = React.useState(baseRoutes);

    // 处理动态路由
    useEffect(() => {
        if (token && menus.length > 0) {
            const filteredMenus = adaptMenuToRouteFormat(menus);
            const newRoutes = addDynamicRoutes(filteredMenus, [...baseRoutes]);
            setRoutes(newRoutes);
        }
    }, [token, menus]);

    // 路由守卫
    useEffect(() => {
        // 如果未登录且访问需要认证的路由，重定向到登录页
        if (!token && location.pathname !== '/login') {
            navigate('/login', { replace: true });
        }
    }, [token, location.pathname, navigate]);

    // 路由组件
    const element = useRoutes(routes);

    return (
        <Suspense fallback={<Spin size="large" className="global-spin" />}>
            {element}
        </Suspense>
    );
};

export default Router;